package com.muye.dianli.activity;

import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.entity.mime.content.StringBody;

import android.R.integer;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.muye.adapter.CommentListAdapter;
import com.muye.adapter.CommodityListAdapter;
import com.muye.adapter.LinkageCommodityListParentAdapter;
import com.muye.constant.C;
import com.muye.constant.ConstantPersonalInfo;
import com.muye.constant.U;
import com.muye.dianli.BaseActivity;
import com.muye.dianli.R;
import com.muye.field.CommentListField;
import com.muye.field.CommodityListData;
import com.muye.field.CommodityListField;
import com.muye.field.LinkageCommodityListData;
import com.zvezda.algorithm.utils.MD5;
import com.zvezda.http.utils.HttpConst;
import com.zvezda.http.utils.KeyValue;
import com.zvezda.http.utils.RequestHttpListener;
import com.zvezda.http.utils.RequestHttpPostThread;

/**
 * 联动商品列表
 * 
 * @author TangChao
 *
 */
public class LinkageCommidityListActivity extends BaseActivity implements OnClickListener, OnKeyListener
{
	/**
	 * 请求数据线程
	 */
	private RequestHttpPostThread requestHttpPostThread;
	
	/**
	 * 父类型列表
	 */
	private ListView typeParentList;
	
	/**
	 * 父类型列表布局
	 */
	private LinearLayout linearParent;
	
	/**
	 * 子类型列表
	 */
	private ListView typeChildList;
	
	/**
	 * 子类型列表布局
	 */
	private LinearLayout linearChild;
	
	/**
	 * 父类数据
	 */
	private List<LinkageCommodityListData> arrayList;
	
	/**
	 * 子类数据
	 */
	private List<LinkageCommodityListData> dataList;
	
	/**
	 * 子类适配器
	 */
	private LinkageCommodityListParentAdapter childAdapter;
	
	/**
	 * 左联动列表
	 */
	private ListView leftLinkageList;
	
	/**
	 * 右联动列表
	 */
	private ListView rightLinkageList;
	
	/**
	 * 商品列表数据
	 */
	private List<CommodityListData> commodityDataList;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		getWindow().setFormat(PixelFormat.RGBA_8888);
		setContentView(R.layout.linkage_commidity_list_layout);
		File file = new File(C.FILE_PATH);
		if (!file.exists())
		{
			file.mkdirs();
		}
		String titleName = getIntent().getStringExtra("TITLE_NAME");
		if (titleName == null || titleName.equals(""))
		{
			finish();
			return;
		}
		createTitle(titleName);
		initWidget();
		getCategoryList(0, "0", "1", "5", "2");
		getCommodityList(0, "0", "1", "5", "2");
	}
	
	@Override
	protected void onDestroy()
	{
		super.onDestroy();
	}
	
	/**
	 * 初始化标题栏
	 */
	private void createTitle(String str)
	{
		TextView titleName = (TextView) findViewById(R.id.title_bar_name_text_view);
		titleName.setText(str);
		ImageView titleLeftBtn = (ImageView) findViewById(R.id.title_bar_left_image_view);
		titleLeftBtn.setVisibility(View.VISIBLE);
		titleLeftBtn.setImageResource(R.drawable.title_back_icon);
		titleLeftBtn.setOnClickListener(this);
		ImageView titleRightBtn = (ImageView) findViewById(R.id.title_bar_right_image_view);
		titleRightBtn.setVisibility(View.VISIBLE);
		titleRightBtn.setImageResource(R.drawable.main_title_right_icon);
		titleRightBtn.setOnClickListener(this);
	}
	
	/**
	 * 初始化控件
	 */
	private void initWidget()
	{
		// 商品类型左选择框
		TextView commodityLeftText = (TextView) findViewById(R.id.linkage_commidity_list_layout_select_text_left);
		commodityLeftText.setOnClickListener(this);
		/* ======================= */
		linearParent = (LinearLayout) findViewById(R.id.linkage_commidity_list_layout_type_list_parent_linear);
		linearParent.setVisibility(View.INVISIBLE);
		typeParentList = (ListView) findViewById(R.id.linkage_commidity_list_layout_type_list_parent);
		typeParentList.setOnItemClickListener(new OnItemClickListener()
		{
			
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
			{
				getCategoryList(1, arrayList.get(arg2).id, "1", "5", "2");
				linearChild.setVisibility(View.VISIBLE);
			}
		});
		/* ============================ */
		linearChild = (LinearLayout) findViewById(R.id.linkage_commidity_list_layout_type_list_child_linear);
		linearChild.setVisibility(View.INVISIBLE);
		typeChildList = (ListView) findViewById(R.id.linkage_commidity_list_layout_type_list_child);
		typeChildList.setOnItemClickListener(new OnItemClickListener()
		{
			
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
			{
				getCommodityList(1, dataList.get(arg2).id, "1", "5", "2");
				linearParent.setVisibility(View.INVISIBLE);
				linearChild.setVisibility(View.INVISIBLE);
			}
		});
		/* ===================== */
		leftLinkageList = (ListView) findViewById(R.id.linkage_list_left);
		rightLinkageList = (ListView) findViewById(R.id.linkage_list_right);
		leftLinkageList.setOnScrollListener(new OnScrollListener()
		{
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState)
			{
				
			}
			
			@Override
			public void onScroll(AbsListView view, final int firstVisibleItem, int visibleItemCount, int totalItemCount)
			{
				new Handler().postDelayed(new Runnable()
				{
					@Override
					public void run()
					{
						rightLinkageList.setSelectionFromTop(firstVisibleItem, 0);
					}
				}, 100);
			}
		});
		
	}
	
	/**
	 * 请求获取商品类型列表
	 * 
	 * @param i
	 *            表示请求类别 (0 父类 ,1 子类)
	 */
	private void getCategoryList(int i, String classify, String page, String size, String type)
	{
		// C.openPragressDialog(this, this, R.string.in_request_data);
		ArrayList<KeyValue<String, Object>> paramsList = new ArrayList<KeyValue<String, Object>>();
		String str = C.APPID + classify + type + C.CONSTANT;
		try
		{
			paramsList.add(new KeyValue<String, Object>("appId", new StringBody(C.APPID, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("parent", new StringBody(classify, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("type", new StringBody(type, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("sign", new StringBody(MD5.getMD5_32(str), Charset.forName("utf-8"))));
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		if (i == 0)
		{
			requestHttpPostThread = new RequestHttpPostThread(getCategoryParentListListener, U.CATEGORY_LIST, paramsList);
		}
		else if (i == 1)
		{
			requestHttpPostThread = new RequestHttpPostThread(getCategoryChildListListener, U.CATEGORY_LIST, paramsList);
		}
		
		requestHttpPostThread.start();
	}
	
	/**
	 * 请求获取父类商品类型列表返回监听
	 */
	private RequestHttpListener getCategoryParentListListener = new RequestHttpListener()
	{
		
		@Override
		public void requestHttp(Message msg)
		{
			Bundle bundle = msg.getData();
			int result = bundle.getInt(HttpConst.ACTION_RESULT, HttpConst.ACTION_FAIL);
			if (result == HttpConst.ACTION_SUCCESS)
			{
				byte[] dataArr = bundle.getByteArray(HttpConst.DATA_ARR);
				try
				{
					String str = new String(dataArr, "utf-8");
					Log.i(C.TAG, "请求父类商品分类列表结果----->" + str);
					Gson gson = new Gson();
					LinkageCommodityListField item = gson.fromJson(str, LinkageCommodityListField.class);
					arrayList = item.data;
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				Message message = new Message();
				message.what = 0;
				message.arg1 = result;
				handler.sendMessage(message);
			}
		}
	};
	
	/**
	 * 请求获取子类商品类型列表返回监听
	 */
	private RequestHttpListener getCategoryChildListListener = new RequestHttpListener()
	{
		
		@Override
		public void requestHttp(Message msg)
		{
			Bundle bundle = msg.getData();
			int result = bundle.getInt(HttpConst.ACTION_RESULT, HttpConst.ACTION_FAIL);
			if (result == HttpConst.ACTION_SUCCESS)
			{
				byte[] dataArr = bundle.getByteArray(HttpConst.DATA_ARR);
				try
				{
					String str = new String(dataArr, "utf-8");
					Log.i(C.TAG, "请求子类商品分类列表结果----->" + str);
					Gson gson = new Gson();
					LinkageCommodityListField item = gson.fromJson(str, LinkageCommodityListField.class);
					dataList = item.data;
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				Message message = new Message();
				message.what = 1;
				message.arg1 = result;
				handler.sendMessage(message);
			}
		}
	};
	
	/**
	 * 请求获取商品列表
	 * 
	 * @param i
	 *            (0 请求最新 ,1 请求分类)
	 */
	private void getCommodityList(int i, String id, String page, String size, String type)
	{
		C.openPragressDialog(this, this, R.string.in_request_data);
		ArrayList<KeyValue<String, Object>> paramsList = new ArrayList<KeyValue<String, Object>>();
		String str = C.APPID + id + page + size + type + C.CONSTANT;
		try
		{
			paramsList.add(new KeyValue<String, Object>("appId", new StringBody(C.APPID, Charset.forName("utf-8"))));
			if (i == 0)
			{
				paramsList.add(new KeyValue<String, Object>("parent", new StringBody(id, Charset.forName("utf-8"))));
			}
			else if (i == 1)
			{
				paramsList.add(new KeyValue<String, Object>("cid", new StringBody(id, Charset.forName("utf-8"))));
			}
			paramsList.add(new KeyValue<String, Object>("page", new StringBody(page, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("size", new StringBody(size, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("type", new StringBody(type, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("sign", new StringBody(MD5.getMD5_32(str), Charset.forName("utf-8"))));
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		requestHttpPostThread = new RequestHttpPostThread(getCommodityListListener, U.LIST, paramsList);
		requestHttpPostThread.start();
	}
	
	/**
	 * 请求获取商品列表返回监听
	 */
	private RequestHttpListener getCommodityListListener = new RequestHttpListener()
	{
		
		@Override
		public void requestHttp(Message msg)
		{
			Bundle bundle = msg.getData();
			int result = bundle.getInt(HttpConst.ACTION_RESULT, HttpConst.ACTION_FAIL);
			if (result == HttpConst.ACTION_SUCCESS)
			{
				byte[] dataArr = bundle.getByteArray(HttpConst.DATA_ARR);
				try
				{
					String str = new String(dataArr, "utf-8");
					Log.i(C.TAG, "请求商品列表结果----->" + str);
					Gson gson = new Gson();
					CommodityListField item = gson.fromJson(str, CommodityListField.class);
					commodityDataList = item.data;
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				Message message = new Message();
				message.what = 2;
				message.arg1 = result;
				handler.sendMessage(message);
			}
		}
	};
	
	/**
	 * 处理数据
	 */
	private Handler handler = new Handler()
	{
		
		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			C.closePragressDialog();
			switch (msg.what)
			{
				case 0:// 请求父类列表
					switch (msg.arg1)
					{
						case HttpConst.ACTION_SUCCESS:
							/**
							 * 父类适配器
							 */
							LinkageCommodityListParentAdapter parentAdapter = new LinkageCommodityListParentAdapter(arrayList,
									LinkageCommidityListActivity.this);
							typeParentList.setAdapter(parentAdapter);
							break;
						case HttpConst.ACTION_FAIL:
							C.showToast(getApplicationContext(), "请求失败,请重试");
							break;
						default:
							break;
					}
					break;
				case 1:// 请求子类列表
					switch (msg.arg1)
					{
						case HttpConst.ACTION_SUCCESS:
							childAdapter = new LinkageCommodityListParentAdapter(dataList, LinkageCommidityListActivity.this);
							typeChildList.setAdapter(childAdapter);
							childAdapter.notifyDataSetChanged();
							break;
						case HttpConst.ACTION_FAIL:
							C.showToast(getApplicationContext(), "请求失败,请重试");
							break;
						default:
							break;
					}
					break;
				case 2:// 请求商品列表
					switch (msg.arg1)
					{
						case HttpConst.ACTION_SUCCESS:
							CommodityListAdapter adapter = new CommodityListAdapter(C.FILE_PATH, commodityDataList,
									LinkageCommidityListActivity.this);
							leftLinkageList.setAdapter(adapter);
							rightLinkageList.setAdapter(adapter);
							break;
						case HttpConst.ACTION_FAIL:
							C.showToast(getApplicationContext(), "请求失败,请重试");
							break;
						default:
							break;
					}
					break;
				default:
					break;
			}
		}
	};
	
	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
			case R.id.title_bar_right_image_view:
				finish();
				break;
			case R.id.linkage_commidity_list_layout_select_text_left:// 左选择框
				// if (typeParentList.getVisibility() == View.GONE && typeChildList.getVisibility() ==
				// View.GONE)
				// {
				linearParent.setVisibility(View.VISIBLE);
				// }
				// else
				// {
				// typeParentList.setVisibility(View.GONE);
				// typeChildList.setVisibility(View.GONE);
				// }
				break;
			case R.id.linkage_commidity_list_layout_select_text_right:// 右选择框
				break;
			
			default:
				break;
		}
	}
	
	@Override
	public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event)
	{
		if (requestHttpPostThread != null)
		{
			requestHttpPostThread.interrupt();
			requestHttpPostThread.setRequestHttpListener(null);
		}
		return false;
	}
}
